package cn.kevinking.auth.util;

import cn.kevinking.auth.config.properties.BfzJwtProperties;
import cn.kevinking.auth.domain.LoginUserAdapter;
import cn.kevinking.auth.entity.BfzUser;
import cn.kevinking.common.util.BfzCipherUtils;
import cn.kevinking.common.util.BfzDateTimeUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * utility class for jwt
 *
 * @author kevinking
 * @since 02 May 2025
 */
@Component
public class JwtUtils {

	private static JwtUtils INSTANCE;

	@Autowired
	private BfzJwtProperties jwtProperties;

	/** private key for server */
	private static final String PRIVATE_KEY = "!bfz-auth&25^";

	public static String createToken(BfzUser user) {
		// recommend using LocalDateTime instead of LocalDate as adding seconds
		LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
		return Jwts.builder()
				.subject(user.getUid())
				.claims(getDefaultClaimFromLoginUser(user))
				.issuer(INSTANCE.jwtProperties.getIss())
				.issuedAt(BfzDateTimeUtils.fromLocalDateTime(now))
				.expiration(BfzDateTimeUtils.fromLocalDateTime(now.plusSeconds(INSTANCE.jwtProperties.getExpireSecond())))
				.signWith(BfzCipherUtils.secretByAes(PRIVATE_KEY))
				.compact();
	}

	private static Map<String, ?> getDefaultClaimFromLoginUser(BfzUser user) {
		Map<String, Object> claims = new HashMap<>(1);
		return claims;
	}

	@PostConstruct
	private void init() {
		INSTANCE = this;
		INSTANCE.jwtProperties = this.jwtProperties;
	}
}
